package com.store.satring.dos;
import java.util.Date;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.PersistenceContext;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Version;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.transaction.annotation.Transactional;

@Entity
@Configurable
public class Customer {

    /**
     */
    @NotNull
    @Size(min = 2)
    private String name;

    /**
     */
    private String mobileNo;

    /**
     */
    private String emailId;

    /**
     */
    private String address;

    /**
     */
    private String createdBy;

    /**
     */
    private String updatedBy;
    
    private boolean store;

    /**
     */
    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(style = "M-")
    private Date createdOn;

    /**
     */
    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(style = "M-")
    private Date updatedOn;

	@Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;

	@Version
    @Column(name = "version")
    private Integer version;

	public Long getId() {
        return this.id;
    }

	public void setId(Long id) {
        this.id = id;
    }

	public Integer getVersion() {
        return this.version;
    }

	public void setVersion(Integer version) {
        this.version = version;
    }

	public String getName() {
        return this.name;
    }

	public void setName(String name) {
        this.name = name;
    }

	public String getMobileNo() {
        return this.mobileNo;
    }

	public void setMobileNo(String mobileNo) {
        this.mobileNo = mobileNo;
    }

	public String getEmailId() {
        return this.emailId;
    }

	public void setEmailId(String emailId) {
        this.emailId = emailId;
    }

	public String getAddress() {
        return this.address;
    }

	public void setAddress(String address) {
        this.address = address;
    }

	public String getCreatedBy() {
        return this.createdBy;
    }

	public void setCreatedBy(String createdBy) {
        this.createdBy = createdBy;
    }

	public String getUpdatedBy() {
        return this.updatedBy;
    }

	public void setUpdatedBy(String updatedBy) {
        this.updatedBy = updatedBy;
    }

	public Date getCreatedOn() {
        return this.createdOn;
    }

	public void setCreatedOn(Date createdOn) {
        this.createdOn = createdOn;
    }

	public Date getUpdatedOn() {
        return this.updatedOn;
    }

	public void setUpdatedOn(Date updatedOn) {
        this.updatedOn = updatedOn;
    }

	public boolean isStore() {
		return store;
	}

	public void setStore(boolean store) {
		this.store = store;
	}

	public String toString() {
        return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
    }

	@PersistenceContext
    transient EntityManager entityManager;

	public static final List<String> fieldNames4OrderClauseFilter = java.util.Arrays.asList("name", "mobileNo", "emailId", "address", "createdBy", "updatedBy", "createdOn", "updatedOn", "store");

	public static final EntityManager entityManager() {
        EntityManager em = new Customer().entityManager;
        if (em == null) throw new IllegalStateException("Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)");
        return em;
    }

	public static long countCustomers() {
        return entityManager().createQuery("SELECT COUNT(o) FROM Customer o where o.store = 0", Long.class).getSingleResult();
    }

	public static List<Customer> findAllCustomers() {
        return entityManager().createQuery("SELECT o FROM Customer o where o.store = 0", Customer.class).getResultList();
    }

	public static List<Customer> findAllCustomers(String sortFieldName, String sortOrder) {
        String jpaQuery = "SELECT o FROM Customer o where o.store = 0";
        if (fieldNames4OrderClauseFilter.contains(sortFieldName)) {
            jpaQuery = jpaQuery + " ORDER BY " + sortFieldName;
            if ("ASC".equalsIgnoreCase(sortOrder) || "DESC".equalsIgnoreCase(sortOrder)) {
                jpaQuery = jpaQuery + " " + sortOrder;
            }
        }
        return entityManager().createQuery(jpaQuery, Customer.class).getResultList();
    }

	public static Customer findCustomer(Long id) {
        if (id == null) return null;
        return entityManager().find(Customer.class, id);
    }

	public static List<Customer> findCustomerEntries(int firstResult, int maxResults) {
        return entityManager().createQuery("SELECT o FROM Customer o  where o.store = 0", Customer.class).setFirstResult(firstResult).setMaxResults(maxResults).getResultList();
    }

	public static List<Customer> findCustomerEntries(int firstResult, int maxResults, String sortFieldName, String sortOrder) {
        String jpaQuery = "SELECT o FROM Customer o  where o.store = 0";
        if (fieldNames4OrderClauseFilter.contains(sortFieldName)) {
            jpaQuery = jpaQuery + " ORDER BY " + sortFieldName;
            if ("ASC".equalsIgnoreCase(sortOrder) || "DESC".equalsIgnoreCase(sortOrder)) {
                jpaQuery = jpaQuery + " " + sortOrder;
            }
        }
        return entityManager().createQuery(jpaQuery, Customer.class).setFirstResult(firstResult).setMaxResults(maxResults).getResultList();
    }

	public static Customer findStoreCustomer() {
		EntityManager em = Invoice.entityManager();
		String jpaQuery = " select id from customer where store = 1";
		List resultList = em.createNativeQuery(jpaQuery).getResultList();
		if (resultList.size() > 1) {
			throw new IllegalStateException(
					"More than one Customer exists in the system with store value 1. Its an illegal State. Please contact to your admin.");
		} else if (resultList.size() == 0) {
			throw new IllegalStateException(
					"No Customer exists in the system with store value 1. Its an illegal State. Please contact to your admin.");
		}
		return findCustomer(Long.parseLong(resultList.get(0).toString()));
	}

	@Transactional
    public void persist() {
        if (this.entityManager == null) this.entityManager = entityManager();
        this.entityManager.persist(this);
    }

	@Transactional
    public void remove() {
        if (this.entityManager == null) this.entityManager = entityManager();
        if (this.entityManager.contains(this)) {
            this.entityManager.remove(this);
        } else {
            Customer attached = Customer.findCustomer(this.id);
            this.entityManager.remove(attached);
        }
    }

	@Transactional
    public void flush() {
        if (this.entityManager == null) this.entityManager = entityManager();
        this.entityManager.flush();
    }

	@Transactional
    public void clear() {
        if (this.entityManager == null) this.entityManager = entityManager();
        this.entityManager.clear();
    }

	@Transactional
    public Customer merge() {
        if (this.entityManager == null) this.entityManager = entityManager();
        Customer merged = this.entityManager.merge(this);
        this.entityManager.flush();
        return merged;
    }
}
